package com.hy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hy.entity.PointsSettings;
import com.hy.mapper.SysPointsSettingsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
public class SysPointsSettingsServiceImpl implements SysPointsSettingsService {
    @Autowired
    private SysPointsSettingsMapper sysPointsSettingsMapper;

    /**
     * 获取所有积分设置
     * @return 积分设置列表
     */
    @Override
    public List<PointsSettings> getSettings() {
        // 查询所有未删除的积分设置（假设delete_flag字段存在，若无则忽略）
        QueryWrapper<PointsSettings> queryWrapper = new QueryWrapper<>();
        // queryWrapper.eq("delete_flag", 0); // 若有逻辑删除字段请启用
        return sysPointsSettingsMapper.selectList(queryWrapper);
    }

    /**
     * 更新积分设置（支持批量新增/更新）
     * @param settings 积分设置列表
     */
    @Override
    @Transactional // 添加事务支持
    public void updateSettings(List<PointsSettings> settings) {
        if (settings == null || settings.isEmpty()) {
            throw new IllegalArgumentException("积分设置列表不能为空");
        }

        settings.forEach(setting -> {
            // 校验必填字段
            if (setting.getSettingKey() == null || setting.getSettingValue() == null) {
                throw new IllegalArgumentException("设置键和值不能为空");
            }

            // 根据设置键查询是否存在现有记录
            PointsSettings existingSetting = sysPointsSettingsMapper.selectOne(
                    new QueryWrapper<PointsSettings>()
                            .eq("setting_key", setting.getSettingKey())
                    // .eq("delete_flag", 0) // 若有逻辑删除字段请启用
            );

            // 存在则更新，不存在则新增
            if (existingSetting != null) {
                // 更新属性
                existingSetting.setSettingValue(setting.getSettingValue());
                existingSetting.setSettingDescription(setting.getSettingDescription());
                existingSetting.setUpdateTime(new Date());
                sysPointsSettingsMapper.updateById(existingSetting);
            } else {
                // 新增记录
                setting.setCreateTime(new Date());
                setting.setUpdateTime(new Date());
                // setting.setDeleteFlag(0); // 若有逻辑删除字段请启用
                sysPointsSettingsMapper.insert(setting);
            }
        });
    }

}
